<template>
  <div class="website-tree" :style="{ width: width ? width + 'px' : 'auto' }">
    <el-row v-if="showFilter" :gutter="10">
      <el-col :span="operation.showTreeBtn ? 18 : 24">
        <el-input
          v-model="filterText"
          :placeholder="$t('输入关键字进行过滤')"
          clearable
          @input="searchEvent()"
        />
      </el-col>
      <el-col v-if="operation.showTreeBtn" :span="6">
        <slot name="tree-add-button"></slot>
      </el-col>
    </el-row>
    <el-scrollbar :style="{ height: height || treeHeight }">
      <vxe-table
        ref="websiteTree"
        size="small"
        :row-id="rowId"
        border="none"
        show-overflow
        :row-config="{ isCurrent: true }"
        :show-header="false"
        :data="filterTreeData"
        :radio-config="{
          labelField: 'label',
          checkRowKey,
          checkMethod: checkMethod,
        }"
        :checkbox-config="{
          labelField: 'label',
          reserve: true,
          checkRowKeys,
          checkStrictly: checkStrictly,
          checkMethod: checkMethod,
        }"
        :cell-style="{ height: '35px' }"
        :loading="loading || cusLoadings"
        :tree-config="{
          showLine: true,
          expandAll: expandAll,
          iconOpen: 'el-icon-caret-bottom',
          iconClose: 'el-icon-caret-right',
        }"
        @current-change="currentChange"
        @radio-change="radioChange"
        @checkbox-change="checkboxChange"
      >
        <vxe-column v-if="treeSelectType === 'radio'" type="radio" tree-node>
          <template #radio="{ row, checked }">
            <div
              class="tree-label"
              :class="{ 'is-disabled': disabledChecked(row) }"
              @click="handleLabelClick(row)"
            >
              <i
                :class="!checked ? 'el-icon-folder' : 'el-icon-folder-checked'"
                class="radio-select-icon"
              ></i>
              <span>{{ row.label }}</span>
            </div>
          </template>
        </vxe-column>
        <vxe-column
          v-if="treeSelectType === 'checkbox'"
          type="checkbox"
          tree-node
        >
          <template #default="{ row }">
            <span>{{ row.label }}</span>
          </template>
        </vxe-column>
        <vxe-column
          v-if="operation.data"
          :title="$t('操作')"
          :width="operation.width + 'px'"
        >
          <template #default="{ row }">
            <vxe-button
              v-for="item in operation.data"
              :key="item.title"
              style="margin-left: 3px"
              type="text"
              :icon="item.icon"
              :title="item.title"
              @click="handleClick(item, row)"
            />
          </template>
        </vxe-column>
      </vxe-table>
    </el-scrollbar>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import { list } from "@/api/organization/index";
import { setContentHeight } from "@/utils/mUtils";
import { VxeTableInstance } from "vxe-table";
import * as _searchTree from "xe-utils/searchTree";
import includes from "xe-utils/includes";
import toValueString from "xe-utils/toValueString";
defineOptions({
  name: "WebsiteTree",
  inheritAttrs: false,
});
const props = defineProps({
  // 组件宽度
  width: {
    type: [Number || String],
    default: "",
  },
  // 组件高度
  height: {
    type: String,
    default: "",
  },
  // 操作按钮
  operation: {
    type: Object,
    default: function () {
      return {};
    },
  },
  // 自定义树结构数据
  treeCusData: {
    type: Array,
    default: function () {
      return null;
    },
  },
  // 自定义加载状态
  cusLoading: {
    type: Boolean,
    default: false,
  },
  // 树形结构区分单选还是多选
  treeSelectType: {
    type: String,
    default: "radio",
  },
  // 选中的数据
  checkedRowKeys: {
    type: Array,
    default: () => {
      return [];
    },
  },
  checkRowKey: {
    type: String,
    default: () => {
      return "";
    },
  },
  // 行id
  rowId: {
    type: String,
    default: "id",
  },
  // 是否显示筛选框
  showFilter: {
    type: Boolean,
    default: true,
  },
  // 自定义元素的高度
  cusHeight: {
    type: Number,
    default: 0,
  },
  // 筛选参数
  filterValue: {
    type: String,
    default: "",
  },
  // 是否展开全部
  expandAll: {
    type: Boolean,
    default: true,
  },
  // 父子不关联
  checkStrictly: {
    type: Boolean,
    default: false,
  },
  // 禁用函数
  checkMethod: {
    type: () => Boolean,
    default: () => {
      return null;
    },
  },
});
const cusLoadings = ref(false);
const treeData= ref([]);
const loading = ref(false);
const filterText = ref("");
const filterTreeData = ref([]);
const treeHeight = ref("");
const checkRowKeys = props.checkedRowKeys;
const disabledCheckKeys = ref([]);
const emit = defineEmits([
  "handleNodeClick",
  "handleCheckboxChange",
  "handleLabelClick",
  "dataObtained",
]);
const websiteTree = ref();
watch(
  () => props.treeCusData,
  (newVal) => {
    if (!newVal) return;
    treeData.value = newVal;
    searchEvent();
  }
);
watch(
  () => props.cusLoading,
  (newVal) => {
    cusLoadings.value = newVal;
  },
  { immediate: true }
);
watch(
  () => props.filterValue,
  (newVal) => {
    searchEvent(newVal);
  }
);
// 获取网点数据
async function getWebsiteData() {
  loading.value = true;
  try {
    const res = await list();
    treeData.value = formatterLabel(res.data);
    emit("dataObtained", treeData.value);
    searchEvent();
    loading.value = false;
  } catch {
    loading.value = false;
  }
}
// 格式化树
function formatterLabel(data) {
  if (data && data.length > 0) {
    data.forEach((it) => {
      it.name = it.label;
      it.label = `${it.label} (${it.code})`;
      if (it.children) {
        formatterLabel(it.children);
      }
    });
  }
  return data;
}
// 模糊查询函数
function searchTree(treeData, filterName) {
  return _searchTree(
    treeData,
    (node) => {
      if (node.code === "0000") {
        // 此时代表集团总部
        return false;
      }
      return includes(node.label, filterName);
    },
    {
      children: "children",
    }
  );
}
function searchEvent(val) {
  let filterName = "";
  let searchText = "";
  if (val) {
    searchText = val;
  } else {
    searchText = filterText.value;
  }
  filterName = toValueString(searchText).trim().toLowerCase();

  if (filterName) {
    // const filterRE = new RegExp(filterName, "gi");
    // const options = { children: "children" };
    // const searchProps = ["label"];
    // const rest = XEUtils.searchTree(
    //   treeData.value,
    //   (item) =>
    //     searchProps.some(
    //       (key) =>
    //         XEUtils.toValueString(item[key]).toLowerCase().indexOf(filterName) >
    //         -1
    //     ),
    //   options
    // );
    const rest = searchTree(treeData.value, filterName);
    console.log(rest, 5555);
    // XEUtils.eachTree(
    //   rest,
    //   (item) => {
    //     searchProps.forEach((key) => {
    //       item[key] = XEUtils.toValueString(item[key]).replace(
    //         filterRE,
    //         // (match) => `<span class="keyword-lighten">${match}</span>`
    //         (match) => `${match}`
    //       );
    //     });
    //   },
    //   options
    // );
    filterTreeData.value = rest;
  } else {
    filterTreeData.value = treeData.value;
  }
  // 搜索之后默认展开所有子节点
  setAllTreeExpand(true);
}
function currentChange({ row }) {
  if (props.treeSelectType === "radio" && !disabledChecked(row)) {
    websiteTree.value && websiteTree.value.setRadioRow(row);
    emit("handleNodeClick", row);
  }
}
function radioChange({ row }) {
  websiteTree.value && websiteTree.value.setCurrentRow(row);
  emit("handleNodeClick", row);
}
function checkboxChange({ row }) {
  emit("handleCheckboxChange", row);
}
function getCheckboxRecords() {
  return websiteTree.value && websiteTree.value.getCheckboxRecords();
}
// function setCheckboxRow(rows: any, checked: any) {
//   websiteTree.value && websiteTree.value.setCheckboxRow(rows, checked);
// }
function computTreeHeight() {
  return setContentHeight(60 + props.cusHeight);
}
function setAllTreeExpand(checked) {
  nextTick(() => {
    websiteTree.value && websiteTree.value.setAllTreeExpand(checked);
  });
}
function handleLabelClick(row) {
  if (!disabledChecked(row)) {
    emit("handleLabelClick", row);
  }
}
function handleClick(item, row) {
  if (item.handleClick) {
    item.handleClick(row);
  }
}
function disabledChecked(row) {
  return (
    disabledCheckKeys.value &&
    disabledCheckKeys.value.includes(row[props.rowId])
  );
}
function setCurrentRow(row) {
  websiteTree.value && websiteTree.value.setCurrentRow(row);
}
onMounted(() => {
  nextTick(() => {
    treeHeight.value = computTreeHeight();
  });
  if (!props.treeCusData) {
    getWebsiteData();
  }
});
defineExpose({
  getCheckboxRecords,
  setCurrentRow,
});
</script>
<style lang="scss" scoped>
:deep() {
  .keyword-lighten {
    color: #000;
    background-color: #ff0;
  }

  .vxe-button.type--text {
    padding-top: 3px;
    padding-bottom: 3px;
  }

}

.website-tree {
  padding: 5px;
  // background-color: #fff;
  .radio-select-icon {
    margin-right: 10px;
    font-size: 16px;
  }

  .tree-label {
    cursor: pointer;

    &.is-disabled {
      color: #a2a5a7;
      cursor: default;
    }
  }
}
</style>
